﻿/*
  Version: MPL 1.1/GPL 2.0/LGPL 2.1
 
  The contents of this file are subject to the Mozilla Public License Version
  1.1 (the "License"); you may not use this file except in compliance with
  the License. You may obtain a copy of the License at
  http://www.mozilla.org/MPL/
  
  Software distributed under the License is distributed on an "AS IS" basis,
  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  for the specific language governing rights and limitations under the
  License.
  
  The Original Code is [maashaack framework].
  
  The Initial Developers of the Original Code are
  Zwetan Kjukov <zwetan@gmail.com> and Marc Alcaraz <ekameleon@gmail.com>.
  Portions created by the Initial Developers are Copyright (C) 2006-2014
  the Initial Developers. All Rights Reserved.
  
  Contributor(s):
  
  Alternatively, the contents of this file may be used under the terms of
  either the GNU General Public License Version 2 or later (the "GPL"), or
  the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  in which case the provisions of the GPL or the LGPL are applicable instead
  of those above. If you wish to allow use of your version of this file only
  under the terms of either the GPL or the LGPL, and not to allow others to
  use your version of this file under the terms of the MPL, indicate your
  decision by deleting the provisions above and replace them with the notice
  and other provisions required by the LGPL or the GPL. If you do not delete
  the provisions above, a recipient may use your version of this file under
  the terms of any one of the MPL, the GPL or the LGPL.
 */
package molecule.render.starling.display
{
    import molecule.render.starling.textures.Scale9Texture;

    import starling.core.RenderSupport;
    import starling.display.DisplayObject;
    import starling.display.Image;
    import starling.display.QuadBatch;
    import starling.display.Sprite;
    import starling.events.Event;
    import starling.textures.Texture;
    import starling.textures.TextureSmoothing;
    import starling.utils.MatrixUtil;

    import flash.geom.Matrix;
    import flash.geom.Point;
    import flash.geom.Rectangle;
    
    /**
     * Scales an image with nine regions to maintain the aspect ratio of the corners regions. 
     * The top and bottom regions stretch horizontally, and the left and right regions scale vertically. 
     * The center region stretches in both directions to fill the remaining space.
     */
    public class Scale9Sprite extends Sprite
    {
        /**
         * Creates a new Scale9Sprite instance.
         * @param texture The texture displayed by this sprite.
         * @param scale9Grid The rectangular region that defines the nine scaling regions for the movie clip. If set to null, the entire movie clip scales normally when any scale transformation is applied.
         * @param textureScale The amount to scale the texture. Useful for DPI changes.
         */
        public function Scale9Sprite( texture:Texture = null , scale9Grid:Rectangle = null , textureScale:Number = 1 )
        {
            _scale9Grid   = scale9Grid ;
            _textureScale = textureScale;
            
            this.texture = texture;
            
            readjustSize();
            
            _batch = new QuadBatch();
            _batch.touchable = false;
            
            addChild(_batch);
            
            addEventListener(Event.FLATTEN, _flatten ) ;
        }
        
        /**
         * The color value to pass to the images.
         */
        public function get color():uint
        {
            return _color;
        }
        
        /**
         * @private
         */
        public function set color( value:uint ):void
        {
            if (_color == value)
            {
                return;
            }
            _color   = value;
            _changed = true;
        }
        
        /**
         * @private
         */
        public override function get height():Number
        {
            return _height;
        }
        
        /**
         * @private
         */
        public override function set height(value:Number):void
        {
            if (_height == value)
            {
                return;
            }
            _height  = _hitArea.height = value;
            _changed = true;
        }
        
        
        /**
         * The rectangular region that defines the nine scaling regions for the movie clip. If set to null, the entire movie clip scales normally when any scale transformation is applied.
         */
        public function get scale9Grid():Rectangle
        {
            return _scale9Grid ;
        }
        
        /**
         * @private
         */
        public function set scale9Grid( rectangle:Rectangle ):void
        {
            _scale9Grid = rectangle ;
            _updateTexture() ;
        }
        
        /**
         * The smoothing value to pass to the images.
         *
         * @see starling.textures.TextureSmoothing
         */
        public function get smoothing():String
        {
            return _smoothing;
        }
        
        /**
         * @private
         */
        public function set smoothing(value:String):void
        {
            if (_smoothing == value)
            {
                return;
            }
            _smoothing = value;
            _changed   = true;
        }
        
        /**
         * The textures displayed by this image.
         */
        public function get texture():Texture
        {
            return _texture ;
        }
        
        /**
         * @private
         */
        public function set texture( value:Texture ):void
        {
            if ( _texture == value )
            {
                return;
            }
            _texture = value ;
            _updateTexture() ;
        }
        
        /**
         * The amount to scale the texture. Useful for DPI changes.
         */
        public function get textureScale():Number
        {
            return _textureScale;
        }
        
        /**
         * @private
         */
        public function set textureScale(value:Number):void
        {
            if (_textureScale == value)
            {
                return;
            }
            _textureScale = value;
            _changed = true;
        }
        
        /**
         * @private
         */
        public override function get width():Number
        {
            return _width;
        }
        
        /**
         * @private
         */
        public override function set width( value:Number ):void
        {
            if (_width == value)
            {
                return;
            }
            _width = _hitArea.width = value;
            _changed = true;
        }
        
        /**
         * @private
         */
        public override function flatten():void
        {
            _update();
            super.flatten();
        }
        
        /**
         * @private
         */
        public override function getBounds(targetSpace:DisplayObject, resultRect:Rectangle = null):Rectangle
        {
            if (!resultRect)
            {
                resultRect = new Rectangle();
            }
            
            var maxX:Number = -Number.MAX_VALUE ;
            var maxY:Number = -Number.MAX_VALUE ;
            
            var minX:Number =  Number.MAX_VALUE ;
            var minY:Number =  Number.MAX_VALUE ;
            
            if (targetSpace == this) // optimization
            {
                minX = _hitArea.x;
                minY = _hitArea.y;
                maxX = _hitArea.x + _hitArea.width;
                maxY = _hitArea.y + _hitArea.height;
            }
            else
            {
                getTransformationMatrix(targetSpace, _matrix);
                
                MatrixUtil.transformCoords(_matrix, _hitArea.x, _hitArea.y, _origin);
                minX = minX < _origin.x ? minX : _origin.x;
                maxX = maxX > _origin.x ? maxX : _origin.x;
                minY = minY < _origin.y ? minY : _origin.y;
                maxY = maxY > _origin.y ? maxY : _origin.y;
                
                MatrixUtil.transformCoords(_matrix, _hitArea.x, _hitArea.y + _hitArea.height, _origin);
                minX = minX < _origin.x ? minX : _origin.x;
                maxX = maxX > _origin.x ? maxX : _origin.x;
                minY = minY < _origin.y ? minY : _origin.y;
                maxY = maxY > _origin.y ? maxY : _origin.y;
                
                MatrixUtil.transformCoords(_matrix, _hitArea.x + _hitArea.width, _hitArea.y, _origin);
                minX = minX < _origin.x ? minX : _origin.x;
                maxX = maxX > _origin.x ? maxX : _origin.x;
                minY = minY < _origin.y ? minY : _origin.y;
                maxY = maxY > _origin.y ? maxY : _origin.y;
                
                MatrixUtil.transformCoords(_matrix, _hitArea.x + _hitArea.width, _hitArea.y + _hitArea.height, _origin);
                minX = minX < _origin.x ? minX : _origin.x;
                maxX = maxX > _origin.x ? maxX : _origin.x;
                minY = minY < _origin.y ? minY : _origin.y;
                maxY = maxY > _origin.y ? maxY : _origin.y;
            }
            
            resultRect.x = minX;
            resultRect.y = minY;
            resultRect.width = maxX - minX;
            resultRect.height = maxY - minY;
            
            return resultRect;
        }
        
        /**
         * @private
         */
        public override function hitTest(localPoint:Point, forTouch:Boolean = false):DisplayObject
        {
            if (forTouch && (!visible || !touchable))
            {
                return null;
            }
            return _hitArea.containsPoint(localPoint) ? this : null;
        }
        
        /**
         * Readjusts the dimensions of the image according to its current textures. 
         * Call this method to synchronize image and texture size after assigning textures with a different size.
         */
        public function readjustSize():void
        {
            if( _frame )
            {
                width  = _frame.width  * _textureScale;
                height = _frame.height * _textureScale;
            }
        }
        
        /**
         * @private
         */
        public override function render(support:RenderSupport, parentAlpha:Number):void
        {
            _update();
            super.render(support, parentAlpha);
        }
        
        /**
         * @private
         */
        private var _batch:QuadBatch;
        
        /**
         * @private
         */
        private var _color:uint = 0xFFFFFF;
        
        /**
         * @private
         */
        private var _frame:Rectangle;
        
        /**
         * @private
         */
        private var _height:Number = NaN;
        
        /**
         * @private
         */
        private var _hitArea:Rectangle = new Rectangle();
        
        /**
         * @private
         */
        private static var _image:Image;
        
        /**
         * @private
         */
        private var _changed:Boolean = true ;
        
        /**
         * @private
         */
        private static const _matrix:Matrix = new Matrix();
        
        /**
         * @private
         */
        private static const _origin:Point = new Point();
        
        /**
         * @private
         */
        private var _scale9Grid:Rectangle ;
        
        /**
         * @private
         */
        private var _smoothing:String = TextureSmoothing.BILINEAR;
        
        /**
         * @private
         */
        private var _s9Texture:Scale9Texture ;
        
        /**
         * @private
         */
        private var _texture:Texture;
        
        /**
         * @private
         */
        private var _textureScale:Number = 1;
        
        /**
         * @private
         */
        private var _width:Number = NaN;
        
        /**
         * @private
         */
        private function _flatten(event:Event):void
        {
            _update();
        }
        
        /**
         * @private
         */
        protected function _update():void
        {
            if ( _changed )
            {
                _batch.reset();
                
                if( _s9Texture )
                {
                    const leftWidth:Number    = _scale9Grid.x * _textureScale;
                    const rightWidth:Number   = (_frame.width - _scale9Grid.x - _scale9Grid.width) * _textureScale;
                    const centerWidth:Number  = _width - leftWidth - rightWidth;
                    
                    const topHeight:Number    = _scale9Grid.y * _textureScale;
                    const bottomHeight:Number = (_frame.height - _scale9Grid.y - _scale9Grid.height) * _textureScale;
                    const middleHeight:Number = _height - topHeight - bottomHeight;
                    
                    _image.smoothing = _smoothing ;
                    _image.color     = _color ;
                    
                    if ( topHeight > 0 )
                    {
                        _image.texture = _s9Texture.topLeft;
                        _image.readjustSize();
                        _image.scaleX = _image.scaleY = _textureScale;
                        _image.x = leftWidth - _image.width;
                        _image.y = topHeight - _image.height;
                        
                        if (leftWidth > 0)
                        {
                            _batch.addImage(_image);
                        }
                        
                        //////////
                        
                        _image.texture = _s9Texture.topCenter;
                        _image.readjustSize();
                        _image.scaleX = _image.scaleY = _textureScale;
                        _image.x = leftWidth;
                        _image.y = topHeight - _image.height;
                        _image.width = centerWidth;
                        
                        if (centerWidth > 0)
                        {
                            _batch.addImage(_image);
                        }
                        
                        //////////
                        
                        _image.texture = _s9Texture.topRight;
                        _image.readjustSize();
                        _image.scaleX = _image.scaleY = _textureScale;
                        _image.x = _width - rightWidth;
                        _image.y = topHeight - _image.height;
                        
                        if (rightWidth > 0)
                        {
                            _batch.addImage(_image);
                        }
                    }
                    
                    if ( middleHeight > 0 )
                    {
                        _image.texture = _s9Texture.middleLeft;
                        _image.readjustSize();
                        _image.scaleX = _image.scaleY = _textureScale;
                        _image.x = leftWidth - _image.width;
                        _image.y = topHeight;
                        _image.height = middleHeight;
                        
                        if (leftWidth > 0)
                        {
                            _batch.addImage(_image);
                        }
                        
                        //////////
                        
                        _image.texture = _s9Texture.middleCenter;
                        _image.readjustSize();
                        _image.scaleX = _image.scaleY = _textureScale;
                        _image.x = leftWidth;
                        _image.y = topHeight;
                        _image.width = centerWidth;
                        _image.height = middleHeight;
                        
                        if( centerWidth > 0 )
                        {
                            _batch.addImage(_image);
                        }
                        
                        //////////
                        
                        _image.texture = _s9Texture.middleRight;
                        _image.readjustSize();
                        _image.scaleX = _image.scaleY = _textureScale;
                        _image.x = _width - rightWidth;
                        _image.y = topHeight;
                        _image.height = middleHeight;
                        
                        if ( rightWidth > 0 )
                        {
                            _batch.addImage(_image);
                        }
                    }
                    
                    if ( bottomHeight > 0 )
                    {
                        _image.texture = _s9Texture.bottomLeft;
                        _image.readjustSize();
                        _image.scaleX = _image.scaleY = _textureScale;
                        _image.x = leftWidth - _image.width;
                        _image.y = _height - bottomHeight;
                        
                        if ( leftWidth > 0 )
                        {
                            _batch.addImage(_image);
                        }
                        
                        //////////
                        
                        _image.texture = _s9Texture.bottomCenter;
                        _image.readjustSize();
                        _image.scaleX = _image.scaleY = _textureScale;
                        _image.x = leftWidth;
                        _image.y = _height - bottomHeight;
                        _image.width = centerWidth;
                        
                        if ( centerWidth > 0 )
                        {
                            _batch.addImage(_image);
                        }
                        
                        //////////
                        
                        _image.texture = _s9Texture.bottomRight;
                        _image.readjustSize();
                        _image.scaleX = _image.scaleY = _textureScale;
                        _image.x = _width - rightWidth;
                        _image.y = _height - bottomHeight;
                        
                        if (rightWidth > 0)
                        {
                            _batch.addImage( _image );
                        }
                    }
                }
                else if ( _texture && _image )
                {
                    _image.smoothing = _smoothing ;
                    _image.color     = _color ;
                    
                    _image.texture = _texture ;
                    _image.width = _width * _textureScale ;
                    _image.height = _height * _textureScale ;
                    
                    _batch.addImage( _image );
                }
                
                _changed = false;
            }
        }
        
        /**
         * @private
         */
        protected function _updateTexture():void
        {
            _s9Texture = (_scale9Grid && _texture) ? new Scale9Texture( _texture , _scale9Grid ) : null ;
            _image     = _texture ? new Image( _s9Texture ? _s9Texture.topLeft : _texture ) : null ;
            _frame     = _texture ? _texture.frame : null ;
            if( _frame )
            {
                _width  = _hitArea.width  = _frame.width  * _textureScale;
                _height = _hitArea.height = _frame.height * _textureScale;
            }
            _changed = true;
        }
    }
}